package com.yycx.common.dbinit.listener;

import com.yycx.common.dbinit.DbInitializer;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.apache.ibatis.jdbc.SqlRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: zyf
 * @date: 2018/12/17 14:55
 * @desc: 初始化 创建表
 */
@Slf4j
public class InitTableListener implements ApplicationListener<ApplicationReadyEvent>, Ordered {

    @Autowired
    private DataSource dataSource;
    private SqlRunner sqlRunner;
    private ScriptRunner runner;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {

        Map<String, DbInitializer> beansOfType = event.getApplicationContext().getBeansOfType(DbInitializer.class);
        List<String> tables = new ArrayList<>();
        try {
            sqlRunner = new SqlRunner(dataSource.getConnection());
            runner = new ScriptRunner(dataSource.getConnection());
            log.info("*******************************数据库字段检测***********************************");
            List<Map<String, Object>> maps = sqlRunner.selectAll("SHOW TABLES");
            for (Map<String, Object> map : maps) {
                for (Map.Entry<String, Object> m : map.entrySet()) {
                    tables.add(m.getValue().toString());
                }

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        for (Map.Entry<String, DbInitializer> entry : beansOfType.entrySet()) {
            DbInitializer value = entry.getValue();
            value.dbInit(sqlRunner, runner, tables);
        }

    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

}
